package merkleTree;

import java.math.BigInteger;
import java.util.ArrayList;

public class Source {
	
	public static int digest;
	
	private static boolean checkProof(int elem, ArrayList<Integer> proof) {
		if(proof == null)
			return false;
		int c1 = 0;
		if(Tree.hash(elem) != proof.get(c1))
			return false;
		int c2 = 1;
		while(c2 < proof.size()-1) {
			System.out.println("Checking if : Hash(  Hash(" + proof.get(c1) + ") || Hash(" + proof.get(c2) + ")  ) == Hash(" + proof.get(c2+1) + ")");
			if (Tree.computeHash(proof.get(c1), proof.get(c2)) != proof.get(c2+1)) 
			{
				return false;
			}
			c1 += 2;
			c2 += 2;
		}
		if(digest != proof.get(proof.size()-1))
			return false;
		return true;
	}
	
	public static void main(String[] args) {
		int[] elem = {1,2,3,4,5,6,7,8,9,10,11,12,13};
		Tree root = Tree.createTree(elem);
		// System.out.println(digest);
		// root.printTreeInorder();
		System.out.println("Tree Created as follows : ");
		root.printLevelOrder();
		System.out.println();
		/*
		ArrayList<Integer> proof = Tree.proofMembership(88);
		//System.out.println(Tree.proofMembership(24));
		if(proof != null)
			for(Integer i : proof) {
				System.out.println(i +"\t");
			}
		System.out.println(proof.size());
		System.out.println(checkProof(88, proof));
		for(int i: elem) {
			ArrayList<Integer> proo = Tree.proofMembership(i);
			System.out.println(proo.size() + "\t" + i + "\t" + checkProof(i, proo));
		}
		*/
		/*BigInteger x = new BigInteger("10");
		System.out.println(x.shiftLeft(4).or(BigInteger.TEN));
		*/
		
		root = root.insert(root,14);
		root.printLevelOrder();
		root = root.insert(root,15);
		root.printLevelOrder();
		root = root.insert(root,16);
		root.printLevelOrder();
		try
		{
		root = root.delete(root, 2);
		root.printLevelOrder();
		root = root.delete(root, 5);
		root.printLevelOrder();
		root = root.delete(root, 6);
		root.printLevelOrder();
		root = root.update(root, 4, 40);
		root.printLevelOrder();
		System.out.println();
		digest = root.getHash();
		ArrayList<Integer> proof = Tree.proofMembership(1);
		System.out.println("Verification for element 1 :");
		System.out.println(checkProof(1, proof));
		proof = Tree.proofMembership(7);
		System.out.println("\nVerification for element 7 :");
		System.out.println(checkProof(7, proof));
		proof = Tree.proofMembership(12);
		System.out.println("\nVerification for element 12 : ");
		System.out.println(checkProof(12, proof));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

}
